/**
 * Mock数据生成器
 * 为开发环境提供模拟数据，支持各种业务场景
 */

import {
  Product,
  ProductCategory,
  ProductCondition,
  ProductStatus,
  TransactionMethod,
  ProductImage,
  LocationInfo,
  PublisherInfo,
} from '../types/product';

/**
 * Mock数据配置接口
 */
export interface MockDataConfig {
  /** 商品数量 */
  productCount?: number;
  /** 是否包含图片 */
  includeImages?: boolean;
  /** 默认学校 */
  defaultSchool?: string;
  /** 用户ID前缀 */
  userIdPrefix?: string;
}

/**
 * Mock数据生成器类
 */
export class MockDataGenerator {
  private static instance: MockDataGenerator;
  
  private schoolNames: string[] = [
    '清华大学', '北京大学', '复旦大学', '上海交通大学', 
    '浙江大学', '南京大学', '武汉大学', '中山大学',
    '四川大学', '西安交通大学', '哈尔滨工业大学', '南开大学'
  ];
  
  private campuses: string[] = ['主校区', '东校区', '西校区', '南校区', '北校区'];
  
  private productTitles: Record<ProductCategory, string[]> = {
    [ProductCategory.TEXTBOOKS]: [
      '高等数学教材', '英语四级词汇书', '计算机程序设计教程', '经济学原理',
      '线性代数教材', '大学物理实验指导', '马克思主义基本原理', '中国近代史纲要'
    ],
    [ProductCategory.ELECTRONICS]: [
      '二手笔记本电脑', '智能手机', '蓝牙耳机', '平板电脑',
      '数码相机', '移动硬盘', '键盘鼠标套装', '路由器'
    ],
    [ProductCategory.CLOTHING]: [
      '春秋季外套', '运动鞋', '牛仔裤', '卫衣',
      '羽绒服', '休闲裤', 'T恤衫', '连衣裙'
    ],
    [ProductCategory.DAILY_GOODS]: [
      '保温杯', '台灯', '收纳箱', '床上用品',
      '餐具套装', '洗漱用品', '镜子', '衣架'
    ],
    [ProductCategory.SPORTS]: [
      '篮球', '羽毛球拍', '瑜伽垫', '运动手表',
      '足球', '乒乓球拍', '哑铃', '跳绳'
    ],
    [ProductCategory.STATIONERY]: [
      '笔记本', '文具套装', '计算器', '书架',
      '文件夹', '便签纸', '笔袋', '订书机'
    ],
    [ProductCategory.DORMITORY]: [
      '床垫', '书桌', '衣柜', '电风扇',
      '椅子', '储物柜', '窗帘', '台灯'
    ],
    [ProductCategory.OTHER]: [
      '闲置物品', '小礼品', '手工艺品', '收藏品',
      '乐器', '书籍', '装饰品', '玩具'
    ]
  };
  
  private productDescriptions: Record<ProductCategory, string[]> = {
    [ProductCategory.TEXTBOOKS]: [
      '教材保存完好，笔记清晰，适合学习使用',
      '经典教材版本，内容详实，考试必备',
      '专业课程教材，重点突出，复习资料齐全',
      '基础课程教材，配套习题解答完整'
    ],
    [ProductCategory.ELECTRONICS]: [
      '功能正常，外观良好，适合学生使用',
      '配置适中，运行流畅，性价比高',
      '保养得当，配件齐全，支持验货',
      '轻度使用，成色新，性能稳定'
    ],
    [ProductCategory.CLOTHING]: [
      '尺码标准，穿着舒适，适合校园生活',
      '款式时尚，质量可靠，物超所值',
      '清洗干净，无破损，可试穿',
      '季节性强，搭配多样，实用性强'
    ],
    [ProductCategory.DAILY_GOODS]: [
      '宿舍必备，实用性强，提升生活质量',
      '收纳整理，空间利用，生活便利',
      '品质保证，耐用持久，经济实惠',
      '设计合理，使用方便，清洁卫生'
    ],
    [ProductCategory.SPORTS]: [
      '运动健身，增强体质，校园生活必备',
      '专业器材，安全可靠，锻炼效果好',
      '休闲娱乐，放松身心，社交活动',
      '团队合作，竞技比赛，培养兴趣'
    ],
    [ProductCategory.STATIONERY]: [
      '学习工具，提高效率，学业有成',
      '设计精美，实用性强，书写流畅',
      '组织整理，文件管理，学习有序',
      '创意设计，激发灵感，创作无限'
    ],
    [ProductCategory.DORMITORY]: [
      '宿舍改造，空间优化，舒适生活',
      '家具齐全，布置合理，温馨环境',
      '实用性强，节省空间，性价比高',
      '质量可靠，安装简单，使用方便'
    ],
    [ProductCategory.OTHER]: [
      '兴趣爱好，个性展示，校园文化',
      '创意设计，手工制作，独特魅力',
      '收藏价值，纪念意义，情感寄托',
      '闲置利用，资源共享，环保节约'
    ]
  };

  private constructor() {}

  /**
   * 获取单例实例
   */
  public static getInstance(): MockDataGenerator {
    if (!MockDataGenerator.instance) {
      MockDataGenerator.instance = new MockDataGenerator();
    }
    return MockDataGenerator.instance;
  }

  /**
   * 生成商品数据
   */
  generateProducts(config: MockDataConfig = {}): Product[] {
    const {
      productCount = 50,
      includeImages = true,
      defaultSchool = '清华大学',
      userIdPrefix = 'user'
    } = config;

    const products: Product[] = [];
    const categories = Object.values(ProductCategory);
    const conditions = Object.values(ProductCondition);
    const statuses = Object.values(ProductStatus);

    for (let i = 1; i <= productCount; i++) {
      const category = this.getRandomItem(categories);
      const condition = this.getRandomItem(conditions);
      const status = this.getRandomItem(statuses);
      const school = defaultSchool || this.getRandomItem(this.schoolNames);
      
      const product: Product = {
        id: `product_${i}`,
        title: this.generateProductTitle(category),
        description: this.generateProductDescription(category),
        price: this.generatePrice(category, condition),
        originalPrice: this.generateOriginalPrice(category),
        category,
        condition,
        transactionMethod: this.generateTransactionMethod(),
        images: includeImages ? this.generateProductImages(i) : [],
        location: this.generateLocationInfo(school),
        publisher: this.generatePublisherInfo(userIdPrefix, school, i),
        publishedAt: this.generateRandomDate(30),
        updatedAt: new Date(),
        status,
        viewCount: this.generateViewCount(status),
        favoriteCount: this.generateFavoriteCount(status),
        inquiryCount: this.generateInquiryCount(status),
        tags: this.generateTags(category),
        isNegotiable: Math.random() > 0.3,
        isFreeShipping: Math.random() > 0.7,
        shippingFee: Math.random() > 0.7 ? this.generateShippingFee() : undefined,
        stock: status === ProductStatus.SOLD ? 0 : this.generateStock(),
        isReturnable: Math.random() > 0.8,
        returnPolicy: Math.random() > 0.8 ? '7天内无理由退换货' : undefined,
      };

      products.push(product);
    }

    return products;
  }

  /**
   * 生成特定类别的商品
   */
  generateProductsByCategory(category: ProductCategory, count: number = 10): Product[] {
    const products = this.generateProducts({ productCount: count });
    return products.filter(product => product.category === category);
  }

  /**
   * 生成特定状态的商品
   */
  generateProductsByStatus(status: ProductStatus, count: number = 10): Product[] {
    const products = this.generateProducts({ productCount: count });
    return products.filter(product => product.status === status);
  }

  /**
   * 生成单个商品
   */
  generateSingleProduct(id?: string, category?: ProductCategory): Product {
    const products = this.generateProducts({ productCount: 1 });
    const product = products[0];
    
    if (id) {
      product.id = id;
    }
    
    if (category) {
      product.category = category;
      product.title = this.generateProductTitle(category);
      product.description = this.generateProductDescription(category);
    }
    
    return product;
  }

  // ========== 私有方法 ==========

  private getRandomItem<T>(array: T[]): T {
    return array[Math.floor(Math.random() * array.length)];
  }

  private generateProductTitle(category: ProductCategory): string {
    const titles = this.productTitles[category];
    return this.getRandomItem(titles);
  }

  private generateProductDescription(category: ProductCategory): string {
    const descriptions = this.productDescriptions[category];
    return this.getRandomItem(descriptions);
  }

  private generatePrice(category: ProductCategory, condition: ProductCondition): number {
    const basePrices: Record<ProductCategory, number> = {
      [ProductCategory.TEXTBOOKS]: 50,
      [ProductCategory.ELECTRONICS]: 800,
      [ProductCategory.CLOTHING]: 100,
      [ProductCategory.DAILY_GOODS]: 30,
      [ProductCategory.SPORTS]: 150,
      [ProductCategory.STATIONERY]: 20,
      [ProductCategory.DORMITORY]: 200,
      [ProductCategory.OTHER]: 50,
    };

    const conditionMultipliers: Record<ProductCondition, number> = {
      [ProductCondition.NEW]: 1.0,
      [ProductCondition.LIKE_NEW]: 0.8,
      [ProductCondition.VERY_GOOD]: 0.7,
      [ProductCondition.GOOD]: 0.6,
      [ProductCondition.FAIR]: 0.5,
      [ProductCondition.POOR]: 0.3,
    };

    const basePrice = basePrices[category];
    const multiplier = conditionMultipliers[condition];
    const variation = Math.random() * 0.4 - 0.2; // ±20% 的随机波动

    return Math.round(basePrice * multiplier * (1 + variation));
  }

  private generateOriginalPrice(category: ProductCategory): number {
    const basePrices: Record<ProductCategory, number> = {
      [ProductCategory.TEXTBOOKS]: 80,
      [ProductCategory.ELECTRONICS]: 1200,
      [ProductCategory.CLOTHING]: 200,
      [ProductCategory.DAILY_GOODS]: 50,
      [ProductCategory.SPORTS]: 250,
      [ProductCategory.STATIONERY]: 35,
      [ProductCategory.DORMITORY]: 300,
      [ProductCategory.OTHER]: 80,
    };

    const basePrice = basePrices[category];
    const variation = Math.random() * 0.3 - 0.15; // ±15% 的随机波动

    return Math.round(basePrice * (1 + variation));
  }

  private generateTransactionMethod(): TransactionMethod {
    const methods = Object.values(TransactionMethod);
    return this.getRandomItem(methods);
  }

  private generateProductImages(productIndex: number): ProductImage[] {
    const imageCount = Math.floor(Math.random() * 3) + 1; // 1-3张图片
    const images: ProductImage[] = [];

    for (let i = 0; i < imageCount; i++) {
      images.push({
        id: `img_${productIndex}_${i}`,
        url: `https://picsum.photos/400/300?random=${productIndex}${i}`,
        thumbnailUrl: `https://picsum.photos/200/150?random=${productIndex}${i}`,
        isCover: i === 0,
        uploadedAt: new Date(),
        description: `商品图片 ${i + 1}`,
      });
    }

    return images;
  }

  private generateLocationInfo(school: string): LocationInfo {
    return {
      school,
      campus: this.getRandomItem(this.campuses),
      address: '学生宿舍区',
      longitude: 116.3974 + (Math.random() - 0.5) * 0.1,
      latitude: 39.9093 + (Math.random() - 0.5) * 0.1,
    };
  }

  private generatePublisherInfo(prefix: string, school: string, index: number): PublisherInfo {
    return {
      userId: `${prefix}_${index}`,
      username: `学生${Math.floor(Math.random() * 10000)}`,
      avatar: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70)}`,
      isStudentVerified: Math.random() > 0.3,
      school,
      contactInfo: Math.random() > 0.5 ? {
        phone: `138${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
        wechat: `wx_${Math.random().toString(36).substr(2, 8)}`,
        qq: `${Math.floor(Math.random() * 1000000000)}`,
      } : undefined,
    };
  }

  private generateRandomDate(daysAgo: number): Date {
    const now = Date.now();
    const past = now - daysAgo * 24 * 60 * 60 * 1000;
    return new Date(past + Math.random() * (now - past));
  }

  private generateViewCount(status: ProductStatus): number {
    const baseCounts: Record<ProductStatus, number> = {
      [ProductStatus.ACTIVE]: 100,
      [ProductStatus.INACTIVE]: 50,
      [ProductStatus.SOLD]: 200,
      [ProductStatus.PENDING]: 10,
      [ProductStatus.REJECTED]: 5,
    };

    const baseCount = baseCounts[status];
    return Math.floor(Math.random() * baseCount * 2);
  }

  private generateFavoriteCount(status: ProductStatus): number {
    const baseCounts: Record<ProductStatus, number> = {
      [ProductStatus.ACTIVE]: 10,
      [ProductStatus.INACTIVE]: 5,
      [ProductStatus.SOLD]: 15,
      [ProductStatus.PENDING]: 2,
      [ProductStatus.REJECTED]: 1,
    };

    const baseCount = baseCounts[status];
    return Math.floor(Math.random() * baseCount * 2);
  }

  private generateInquiryCount(status: ProductStatus): number {
    const baseCounts: Record<ProductStatus, number> = {
      [ProductStatus.ACTIVE]: 5,
      [ProductStatus.INACTIVE]: 2,
      [ProductStatus.SOLD]: 8,
      [ProductStatus.PENDING]: 1,
      [ProductStatus.REJECTED]: 0,
    };

    const baseCount = baseCounts[status];
    return Math.floor(Math.random() * baseCount * 2);
  }

  private generateTags(category: ProductCategory): string[] {
    const baseTags = ['校园', '二手', '实惠', '学生'];
    const categoryTags: Record<ProductCategory, string[]> = {
      [ProductCategory.TEXTBOOKS]: ['教材', '学习', '考试'],
      [ProductCategory.ELECTRONICS]: ['数码', '科技', '智能'],
      [ProductCategory.CLOTHING]: ['时尚', '穿搭', '潮流'],
      [ProductCategory.DAILY_GOODS]: ['生活', '实用', '宿舍'],
      [ProductCategory.SPORTS]: ['运动', '健康', '健身'],
      [ProductCategory.STATIONERY]: ['学习', '办公', '文具'],
      [ProductCategory.DORMITORY]: ['宿舍', '家具', '收纳'],
      [ProductCategory.OTHER]: ['闲置', '创意', '收藏'],
    };

    return [...baseTags, ...categoryTags[category]];
  }

  private generateShippingFee(): number {
    return Math.floor(Math.random() * 20) + 5; // 5-25元
  }

  private generateStock(): number {
    return Math.floor(Math.random() * 5) + 1; // 1-5件
  }
}

// 导出单例实例
export const mockDataGenerator = MockDataGenerator.getInstance();

export default MockDataGenerator;